package cn.buk.tms.eotms.security;

import cn.buk.common.Constant;
import cn.buk.common.util.VerifyCodeUtil;
import cn.buk.tms.eotms.dto.DtoLoginStatus;
import cn.buk.tms.eotms.entity.User;
import cn.buk.tms.eotms.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import jakarta.servlet.http.HttpSession;

/**
 *
 * @author yfdai
 * date 2017/3/24
 */
public class LoginUtil {

    private static final Logger logger = LogManager.getLogger(LoginUtil.class);

    private LoginUtil() {

    }

    /**
     *      *
     * @param authenticationManager
     * @param session
     * @param userId
     * @param entId
     * @param username
     * @param password 此处保存的内容为：明文密码使用md5后，再用passwordEncoder.encode
     * @param fullName
     */
    public static void execLoginProcess(AuthenticationManager authenticationManager, HttpSession session, int userId, int entId, String username, String password, String fullName) {
        logger.info("username: {}, password: {}.", username, password);

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

        //调用loadUserByUsername
        Authentication authentication = authenticationManager.authenticate(authRequest);

        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
        securityContext.setAuthentication(authentication);

        logger.info("{} login.", username);
        SecurityContextHolder.setContext(securityContext);

        // 这个非常重要，否则验证后将无法登陆
        session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
        session.setAttribute(Constant.SESSION_USERID, userId);
        session.setAttribute(Constant.SESSION_USERNAME, username);
        session.setAttribute(Constant.SESSION_FULLNAME, fullName);
        session.setAttribute(Constant.SESSION_LOGINED, 1);
        session.setAttribute(Constant.SESSION_ENTERPRISE_ID, entId);
        session.setAttribute("user_roles", authentication.getAuthorities().toString());
    }

    /**
     * 将登录信息保存到redis
     */
    public static void saveLoginInfo2Redis(DtoLoginStatus jsonResult, User u, String savePwd, String remoteAddress, UserService userService) {
        final int enterpriseId = u.getEnterpriseId();
        final String token0 = u.getUsername() + "," + u.getId() + "," + "," + remoteAddress + ", " + System.currentTimeMillis();
        final String token = VerifyCodeUtil.MD5(token0);

        jsonResult.setErrcode(0);
        jsonResult.setUserId(u.getId());
        jsonResult.setUsername(u.getUsername());
        jsonResult.setFullName(u.getEmpname());
        jsonResult.setEnterpriseId(enterpriseId);
        jsonResult.setToken(token);
        jsonResult.setPassword(savePwd);

        //保存token到redis中
        userService.saveToken(jsonResult);
        jsonResult.setPassword("");

        logger.info("username: " + u.getUsername() + ", token: " + token);
    }
}
